package com.ruicar.afs.cloud.apply.pre.loan.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.business.service.ApplyRecordDetailsService;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.contract.enums.CertTypePictureEnum;
import com.ruicar.afs.cloud.apply.contract.enums.IsMainEnum;
import com.ruicar.afs.cloud.apply.contract.enums.UploadIDImageSceneEnum;
import com.ruicar.afs.cloud.apply.contract.service.CreatContractService;
import com.ruicar.afs.cloud.apply.pre.approve.condition.PreApproveCondition;
import com.ruicar.afs.cloud.apply.pre.approve.mapper.PreApproveMapper;
import com.ruicar.afs.cloud.apply.pre.approve.service.PreApproveService;
import com.ruicar.afs.cloud.apply.pre.loan.condition.CustContactsCondition;
import com.ruicar.afs.cloud.apply.pre.loan.condition.CustInfoCondition;
import com.ruicar.afs.cloud.apply.pre.loan.service.*;
import com.ruicar.afs.cloud.apply.pre.loan.service.impl.ApplyOrderInfoServiceImpl;
import com.ruicar.afs.cloud.apply.pre.loan.vo.CustomerListVO;
import com.ruicar.afs.cloud.bizcommon.print.enums.ServiceClientTypeEnum;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.parameter.commom.enums.AProveBusinessTypeEnum;
import com.ruicar.afs.cloud.parameter.commom.enums.CustType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;

/**
 * @description: 客户信息-主借人、共借人、保证人、联系人
 * @author:jihuigeng
 * @date: 2020/5/11 15:21
 */
@Slf4j
@RestController
@RequestMapping("/cust")
@AllArgsConstructor
@Api("客户信息-主借人、共借人、保证人、联系人")
public class ApplyCustInfoController {

    private final ApplyCustContactsService applyCustContactsService;
    private final ApplyCustBaseInfoService applyCustBaseInfoService;
    private final ApplyCustAddressService applyCustAddressService;
    private final ApplyCustPersonalService applyCustPersonalService;
    private final ApplyOrderInfoServiceImpl applyOrderInfoService;
    private final ApplyCarDetailsService applyCarDetailsService;
    private final PreApproveService preApproveService;
    private final PreApproveMapper preApproveMapper;
    private final ApplyRecordDetailsService applyRecordDetailsService;
    private final CreatContractService creatContractService;
    private final ApplyRemindDetailsService applyRemindDetailsService;

    /**
     * 新增
     *
     * @param condition
     * @return
     * @throws ParseException
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/saveCustomerInfo")
    @ApiOperation(value = "新增")
    public IResponse saveCustomerInfo(@RequestBody @NotNull CustInfoCondition condition) throws IOException {

        //获取客户基础信息
        ApplyCustBaseInfo applyCustBaseInfo = condition.getApplyCustBaseInfo();
        //获取客户明细
        ApplyCustPersonalDetail personalDetail = condition.getPersonalDetail();
        //获取地址明细信息
        List<ApplyCustAddressDetails> addressDetailsList = condition.getAddressDetailsList();

        ApplyCarDetails carDetailsByApplyNo = this.applyCarDetailsService.getCarDetailsByApplyNo(condition.getApplyNo());
        if (ObjectUtil.isNotNull(carDetailsByApplyNo)) {
            if (StringUtil.isNotEmpty(carDetailsByApplyNo.getBelongsCertNo())) {
                if (carDetailsByApplyNo.getBelongsCertNo().equals(applyCustBaseInfo.getCertNo())) {
                    return IResponse.fail("车辆所有人和主借人不可为同一人");
                }
            }
        }
        if (applyCustBaseInfo == null) {
            return IResponse.fail("客户基础信息不可为空");
        } else if (personalDetail == null) {
            return IResponse.fail("个人详细信息不可为空");
        } else if (addressDetailsList == null) {
            return IResponse.fail("地址信息不可为空");
        }
        //插入之前，先根据证件号，申请编号，查客户是否已经存在，如果存在就抛错
        List<ApplyCustBaseInfo> list = this.applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(StringUtil.isNotEmpty(condition.getApplyNo()), ApplyCustBaseInfo::getApplyNo, condition.getApplyNo()));
        if (CollectionUtil.isNotEmpty(list)) {
            for (ApplyCustBaseInfo baseInfo : list) {
                //如果和查詢出來的角色不相同
                if (!baseInfo.getCustRole().equals(condition.getCustRole())) {
                    //如果證件號相同
                    if (baseInfo.getCertNo().equals(applyCustBaseInfo.getCertNo())) {
                        return IResponse.fail("客户证件号不可重复");
                    }
                    //如果手機號相同
                    if (baseInfo.getTelPhone().equals(applyCustBaseInfo.getTelPhone())) {
                        return IResponse.fail("客户手机号不可重复");
                    }
                    //如果客户姓名相同
                    if (baseInfo.getCustName().equals(applyCustBaseInfo.getCustName())) {
                        return IResponse.fail("客户姓名不可重复");
                    }
                }
            }
        }
        //保存身份证的正反面
        this.preApproveService.storeCardImage(condition.getFrontIDCard(), condition.getReverseIDCard(), UploadIDImageSceneEnum.CUSTOMER_INFO_ID_CARD_IMAGE_SCENE.getCode(), condition.getCustRole(), condition.getApplyNo());
        applyCustBaseInfo.setCustType(CustType.PERSON.getIndex());
        applyCustBaseInfo.setApplyNo(condition.getApplyNo());
        applyCustBaseInfo.setCustRole(condition.getCustRole());
        applyCustBaseInfo.setCreateBy(SecurityUtils.getUsername());
        applyCustBaseInfo.setCreateTime(new Date());
        //保存客户基础信息
        this.applyCustBaseInfoService.save(applyCustBaseInfo);
        //查询客户基础信息
        ApplyCustBaseInfo info = this.applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(ApplyCustBaseInfo::getApplyNo, condition.getApplyNo())
                .eq(ApplyCustBaseInfo::getCertNo, applyCustBaseInfo.getCertNo()));
        personalDetail.setCreateBy(SecurityUtils.getUsername());
        personalDetail.setCreateTime(new Date());
        personalDetail.setApplyNo(condition.getApplyNo());
        personalDetail.setCustId(info.getId());
        this.applyCustPersonalService.save(personalDetail);
        ApplyCustAddressDetails applyCustAddressDetails = new ApplyCustAddressDetails();
        //获取户籍地址
        String[] permanentAdreess = personalDetail.getPermanentAdreess();
        if (ArrayUtils.isNotEmpty(permanentAdreess)) {
            applyCustAddressDetails.setApplyNo(info.getApplyNo());
            applyCustAddressDetails.setCustId(info.getId());
            //户籍地址设置有效性
            applyCustAddressDetails.setIsMain(IsMainEnum.isMain.getCode());
            applyCustAddressDetails.setDetailAddressTemp(permanentAdreess);
            applyCustAddressDetails.setAddressType(ApplyConstants.PERMANENT_ADDRESS);
            applyCustAddressDetails.setCreateBy(SecurityUtils.getUsername());
            applyCustAddressDetails.setCreateTime(new Date());
            applyCustAddressService.save(applyCustAddressDetails);
        }
        //如果地址信息少于两条，那么就抛错
        if (addressDetailsList.size() < ApplyConstants.TOW_INT) {
            return IResponse.fail("地址信息不可少于两条");
        }
        //保存
        for (ApplyCustAddressDetails addressDetails : addressDetailsList) {
            addressDetails.setCreateBy(SecurityUtils.getUsername());
            addressDetails.setCreateTime(new Date());
            addressDetails.setCustId(info.getId());
            addressDetails.setApplyNo(condition.getApplyNo());
            this.applyCustAddressService.save(addressDetails);
        }
        //如果是主借人，联系人保存
        if (!condition.getCustRole().equals(ApplyConstants.COMMON_BORROWER) && !condition.getCustRole().equals(ApplyConstants.GUARANTOR)) {
            List<ApplyCustContacts> custContactsList = condition.getCustContactsList();
            for (ApplyCustContacts contacts : custContactsList) {
                contacts.setCreateBy(SecurityUtils.getUsername());
                contacts.setCreateTime(new Date());
                contacts.setApplyNo(condition.getApplyNo());
                this.applyCustContactsService.save(contacts);
            }
            //更新订单表内，客户姓名,留言
            ApplyOrderInfo orderInfoByApplyNo = applyOrderInfoService.getOrderInfoByApplyNo(info.getApplyNo());
            orderInfoByApplyNo.setCustName(info.getCustName());
            orderInfoByApplyNo.setRemarks(condition.getRemarks());
            applyOrderInfoService.updateById(orderInfoByApplyNo);
        }
        Map map = new HashMap();
        map.put("id", info.getId());
        return IResponse.success(map);
    }

    /**
     * 获取客户数据:主借人，共借人，担保人
     *
     * @param condition（applyNo,custRole）
     * @return
     */
    @PostMapping(value = "/getCustomerList")
    @ApiOperation(value = "获取客户数据")
    public IResponse<CustomerListVO> getCustomerList(@ModelAttribute CustInfoCondition condition) {
        List resultList = new ArrayList<>();
        PreApproveCondition preApproveCondition = new PreApproveCondition();
        Map<String, String> map = new HashMap<>();

        //查询所有客户信息
        List<ApplyCustBaseInfo> custBaseInfosList = applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(ApplyCustBaseInfo::getApplyNo, condition.getApplyNo()).eq(StringUtil.isNotEmpty(condition.getCustRole()), ApplyCustBaseInfo::getCustRole, condition.getCustRole()));
        Map<String, String> fileId = this.preApproveService.getFileId(null, condition.getApplyNo());
        if (CollectionUtil.isNotEmpty(custBaseInfosList)) {
            custBaseInfosList.forEach(applyCustBaseInfo -> {
                CustomerListVO vo = new CustomerListVO();
                //主借人，查询联系人信息,查询预审批信息
                if (applyCustBaseInfo.getCustRole().equals(ApplyConstants.PRINCIPAL_BORROWER)) {
                    List<ApplyCustContacts> custContactsList = this.applyCustContactsService.getCustContactsList(applyCustBaseInfo.getApplyNo());
                    if (CollectionUtil.isNotEmpty(custContactsList)) {
                        vo.setContactsList(custContactsList);
                    }
                    preApproveCondition.setCustName(applyCustBaseInfo.getCustName());
                    preApproveCondition.setCertNo(applyCustBaseInfo.getCertNo());
                    preApproveCondition.setBusinessType(condition.getBussinessType());
                    preApproveCondition.setCreateBy(SecurityUtils.getUsername());
                    JSONArray jsonArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray(ApplyConstants.DEPT_IDS);
                    if (jsonArray != null) {
                        preApproveCondition.setDeptIds(jsonArray.toJavaList(String.class));
                    }
                    //查询预审批信息
                    List<PreApproveInfo> info = this.preApproveMapper.getPreApproveInfo(preApproveCondition);
                    if (CollectionUtil.isNotEmpty(info)) {
                        for (int i = 0; i < info.size(); i++) {
                            PreApproveInfo preApproveInfo = info.get(i);
                            if (ObjectUtil.isNotNull(preApproveInfo)) {
                                //如果存在电子签约结果，更新入客户主表中
                                if (StringUtil.isNotEmpty(preApproveInfo.getSignResult())) {
                                    applyCustBaseInfo.setSignResult(preApproveInfo.getSignResult());
                                    this.applyCustBaseInfoService.updateById(applyCustBaseInfo);
                                    //将予审批身份证附件信息copy到客户信息一份
                                    Map<String, String> stringMap = this.preApproveService.getFileId(preApproveInfo.getId().toString(), null);
                                    String preBorrowerIdCardFront = stringMap.get("preBorrowerIdCardFront");
                                    String preBorrowerIdCardBack = stringMap.get("preBorrowerIdCardBack");
                                    //保存为主借人信息附件
                                    if (StringUtil.isNotEmpty(preBorrowerIdCardFront)) {
                                        map.put("md5", preBorrowerIdCardFront);
                                        this.preApproveService.setImageStore(CertTypePictureEnum.MAIN_BORROWER_ID_CARD_FRONT.getIndex(), map, applyCustBaseInfo.getApplyNo());
                                    }
                                    if (StringUtil.isNotEmpty(preBorrowerIdCardBack)) {
                                        map.put("md5", preBorrowerIdCardBack);
                                        this.preApproveService.setImageStore(CertTypePictureEnum.MAIN_BORROWER_ID_CARD_BACK.getIndex(), map, applyCustBaseInfo.getApplyNo());
                                    }
                                }
                            }
                        }
                    }
                }
                //根据客户主表id，查询个人客户信息
                ApplyCustPersonalDetail personalDetail = applyCustPersonalService.getOne(Wrappers.<ApplyCustPersonalDetail>query().lambda()
                        .eq(ApplyCustPersonalDetail::getCustId, applyCustBaseInfo.getId()));
                if (ObjectUtil.isNotNull(personalDetail)) {
                    //根据个人客户id，查询多个地址信息
                    List<ApplyCustAddressDetails> custAddressDetailsList = applyCustAddressService.list(Wrappers.<ApplyCustAddressDetails>query().lambda()
                            .eq(ApplyCustAddressDetails::getCustId, personalDetail.getCustId()));
                    //主借人户籍地址
                    if (CollectionUtil.isNotEmpty(custAddressDetailsList)) {
                        personalDetail.setPermanentAdreess(custAddressDetailsList.get(0).getDetailAddressTemp());
                        personalDetail.setPersonalAddressId(custAddressDetailsList.get(0).getId());
                    }
                    vo.setAddressList(custAddressDetailsList);
                    vo.setPersonalInfo(personalDetail);
                }
                vo.setCustBaseInfo(applyCustBaseInfo);
                vo.setIdData(fileId);
                //查询审批玄武退回记录
                List<WorkflowRecordDetails> list = applyRecordDetailsService.list(Wrappers.<WorkflowRecordDetails>query().lambda()
                        .eq(WorkflowRecordDetails::getBusinessNo, condition.getApplyNo())
                        .eq(WorkflowRecordDetails::getApproveResult, AProveBusinessTypeEnum.SUGGEST_REJECT_FINAL.getCode()));
                if (CollectionUtil.isNotEmpty(list)) {
                    vo.setIsSuggestRejectF(WhetherEnum.YES.getCode());
                } else {
                    vo.setIsSuggestRejectF(WhetherEnum.NO.getCode());
                }
                //查询审批流程内退回记录
                List<WorkflowRecordDetails> recordDetails = applyRecordDetailsService.list(Wrappers.<WorkflowRecordDetails>query().lambda()
                        .eq(WorkflowRecordDetails::getBusinessNo, condition.getApplyNo())
                        .eq(WorkflowRecordDetails::getApproveResult, AProveBusinessTypeEnum.BACK.getCode()));
                if (CollectionUtil.isNotEmpty(recordDetails)) {
                    vo.setIsBack(WhetherEnum.YES.getCode());
                } else {
                    vo.setIsBack(WhetherEnum.NO.getCode());
                }
                //查询经销商退回留言记录
                List<ApplyRemindDetails> applyRemindDetailsList = applyRemindDetailsService.list(Wrappers.<ApplyRemindDetails>query().lambda().eq(ApplyRemindDetails::getApplyNo, condition.getApplyNo()).eq(ApplyRemindDetails::getRemindType, AProveBusinessTypeEnum.SEND_BACK_TO_DEALER.getCode()));
                if (CollectionUtil.isNotEmpty(applyRemindDetailsList)) {
                    vo.setIsSendBackToDealer(WhetherEnum.YES.getCode());
                } else {
                    vo.setIsSendBackToDealer(WhetherEnum.NO.getCode());
                }
                resultList.add(vo);
            });
        }
        return IResponse.success(resultList);
    }

    /**
     * 查询联系人信息
     *
     * @param condition
     * @return
     */
    @PostMapping("/getContactList")
    @ApiOperation(value = "获取联系人数据")
    public IResponse<ApplyCustContacts> getContactList(@ModelAttribute CustContactsCondition condition) {
        CustomerListVO customerListVO = new CustomerListVO();
        List<ApplyCustContacts> custContactsList = applyCustContactsService.list(Wrappers.<ApplyCustContacts>query().lambda()
                .eq(StringUtil.isNotEmpty(condition.getApplyNo()), ApplyCustContacts::getApplyNo, condition.getApplyNo()));
        customerListVO.setContactsList(custContactsList);
        return IResponse.success(customerListVO);
    }

    /**
     * 更新主借人，共借人，担保人客户基础信息，详细信息，地址信息,复制时，更新订单表信息
     *
     * @param condition
     * @return
     * @throws ParseException
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/updateCustomerInfo")
    @ApiOperation(value = "更新")
    public IResponse updateCustomerInfo(@RequestBody @NotNull CustInfoCondition condition) throws ParseException {
        //前端传来的要更新的客户基本信息
        ApplyCustBaseInfo applyCustBaseInfo = condition.getApplyCustBaseInfo();
        ApplyCarDetails carDetailsByApplyNo = this.applyCarDetailsService.getCarDetailsByApplyNo(condition.getApplyNo());
        if (ObjectUtil.isNotNull(carDetailsByApplyNo)) {
            if (StringUtil.isNotEmpty(carDetailsByApplyNo.getBelongsCertNo())) {
                if (carDetailsByApplyNo.getBelongsCertNo().equals(applyCustBaseInfo.getCertNo())) {
                    return IResponse.fail("车辆所有人和主借人不可为同一人");
                }
            }
        }
        this.preApproveService.storeCardImage(condition.getFrontIDCard(), condition.getReverseIDCard(), UploadIDImageSceneEnum.CUSTOMER_INFO_ID_CARD_IMAGE_SCENE.getCode(), condition.getCustRole(), condition.getApplyNo());
        List<ApplyCustBaseInfo> list = this.applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(StringUtil.isNotEmpty(condition.getApplyNo()), ApplyCustBaseInfo::getApplyNo, condition.getApplyNo()));
        if (CollectionUtil.isNotEmpty(list)) {
            for (ApplyCustBaseInfo baseInfo : list) {
                //如果是同一角色
                if (baseInfo.getCustRole().equals(applyCustBaseInfo.getCustRole())) {
                    if (!baseInfo.getCustName().equals(applyCustBaseInfo.getCustName())) {
                        //重出标识
                        applyCustBaseInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
                    } else if (!baseInfo.getCertNo().equals(applyCustBaseInfo.getCertNo())) {
                        //重出标识
                        applyCustBaseInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
                    } else if (!baseInfo.getCertType().equals(applyCustBaseInfo.getCertType())) {
                        //重出标识
                        applyCustBaseInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
                    } else if (!baseInfo.getTelPhone().equals(applyCustBaseInfo.getTelPhone())) {
                        //重出标识
                        applyCustBaseInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
                    }
                } else if (!baseInfo.getCustRole().equals(condition.getCustRole())) {
                    //如果和查詢出來的角色不相同
                    //如果證件號相同
                    if (baseInfo.getCertNo().equals(applyCustBaseInfo.getCertNo())) {
                        return IResponse.fail("客户证件号不可重複");
                    }
                    //如果手機號相同
                    if (baseInfo.getTelPhone().equals(applyCustBaseInfo.getTelPhone())) {
                        return IResponse.fail("客户手机号不可重複");
                    }
                    //如果客户姓名相同
                    if (baseInfo.getCustName().equals(applyCustBaseInfo.getCustName())) {
                        return IResponse.fail("客户姓名不可重複");
                    }
                }
            }
        }
        //更新客户基本信息
        applyCustBaseInfo.setUpdateBy(SecurityUtils.getUsername());
        applyCustBaseInfo.setUpdateTime(new Date());
        this.applyCustBaseInfoService.updateById(applyCustBaseInfo);
        //前端传来的要更新的客户明细
        ApplyCustPersonalDetail personalDetail = condition.getPersonalDetail();
        //更新个人明细信息
        personalDetail.setUpdateBy(SecurityUtils.getUsername());
        personalDetail.setUpdateTime(new Date());
        this.applyCustPersonalService.updateById(personalDetail);
        //更新订单表客户姓名,时间，更新人,留言
        ApplyOrderInfo orderInfoByApplyNo = this.applyOrderInfoService.getOrderInfoByApplyNo(applyCustBaseInfo.getApplyNo());
        if (ObjectUtil.isNotNull(orderInfoByApplyNo)) {
            orderInfoByApplyNo.setCustName(applyCustBaseInfo.getCustName());
            orderInfoByApplyNo.setRemarks(condition.getRemarks());
            orderInfoByApplyNo.setUpdateBy(SecurityUtils.getUsername());
            orderInfoByApplyNo.setUpdateTime(new Date());
            this.applyOrderInfoService.updateById(orderInfoByApplyNo);
        }
        //从前端传来的要更新的联系人数据
        List<ApplyCustContacts> custContactsList = condition.getCustContactsList();
        if (CollectionUtil.isNotEmpty(custContactsList)) {
            custContactsList.forEach(applyCustContacts -> {
                if (applyCustContacts.getId() != null) {
                    //更新联系人
                    applyCustContactsService.updateById(applyCustContacts);
                } else {
                    applyCustContacts.setApplyNo(condition.getApplyNo());
                    applyCustContactsService.save(applyCustContacts);
                }
            });
        }
        //前端传来的要更新的地址数据
        List<ApplyCustAddressDetails> addressDetailsList = condition.getAddressDetailsList();
        //先查询地址明细
        List<ApplyCustAddressDetails> detailsList = applyCustAddressService.list(Wrappers.<ApplyCustAddressDetails>query().lambda()
                .eq(ApplyCustAddressDetails::getCustId, applyCustBaseInfo.getId()));
        //遍历出地址id
        for (ApplyCustAddressDetails details : detailsList) {
            //根据传来的addressDetailsList更新地址明细
            for (ApplyCustAddressDetails applyCustAddressDetails : addressDetailsList) {
                if (details.getId().equals(applyCustAddressDetails.getId())) {
                    applyCustAddressDetails.setUpdateBy(SecurityUtils.getUsername());
                    applyCustAddressDetails.setUpdateTime(new Date());
                    applyCustAddressService.updateById(applyCustAddressDetails);
                } else if (details.getId().equals(personalDetail.getPersonalAddressId())) {
                    details.setUpdateBy(SecurityUtils.getUsername());
                    details.setDetailAddressTemp(personalDetail.getPermanentAdreess());
                    details.setUpdateTime(new Date());
                    applyCustAddressService.updateById(details);
                } else if (applyCustAddressDetails.getId() == null) {
                    //如果是更新时，新增地址信息，那么就判断id是否为空，为空，那么就执行保存操作，而不是更新操作
                    applyCustAddressDetails.setCreateBy(SecurityUtils.getUsername());
                    applyCustAddressDetails.setCreateTime(new Date());
                    applyCustAddressDetails.setCustId(applyCustBaseInfo.getId());
                    applyCustAddressDetails.setApplyNo(applyCustBaseInfo.getApplyNo());
                    applyCustAddressService.save(applyCustAddressDetails);
                }
            }
        }
        return IResponse.success("更新成功");
    }

    /**
     * 删除客户信息
     *
     * @param condition
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/deleteCustomerInfo")
    @ApiOperation(value = "删除客户信息")
    public IResponse deleteCustomerInfo(@RequestBody @NotNull CustInfoCondition condition) {
        boolean b = applyCustBaseInfoService.deleteCustomerInfo(condition);
        if (b) {
            return IResponse.success("删除成功");
        }
        return IResponse.fail("删除失败");
    }

    /**
     * 删除地址
     *
     * @param condition
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/deleteAddressInfo")
    @ApiOperation(value = "删除地址")
    public IResponse deleteAddressInfo(@RequestBody @NotNull CustInfoCondition condition) {
        Long id = condition.getId();
        applyCustAddressService.removeById(id);
        return IResponse.success("删除成功");
    }

    /**
     * 删除联系人信息
     *
     * @param condition
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/deleteContectInfo")
    @ApiOperation(value = "删除联系人信息")
    public IResponse deleteContectInfo(@RequestBody @NotNull CustInfoCondition condition) {
        Long id = condition.getId();
        applyCustContactsService.removeById(id);
        return IResponse.success("删除成功");
    }

    /**
     * 保存客户基础信息-app
     *
     * @param condition 客户基础信息
     * @return fileId 附件md5信息
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "保存客户基础信息-app")
    @PostMapping("/saveCustomerBaseInfo")
    public IResponse saveCustomerBaseInfo(@RequestBody @NotNull CustInfoCondition condition) {
        this.applyCustBaseInfoService.saveCustomerBaseInfo(condition);
        Map<String, String> fileId = this.preApproveService.getFileId(null, condition.getApplyNo());
        return IResponse.success(fileId);
    }

    /**
     * 保存工作信息-app
     *
     * @param condition 工作信息
     * @return 保存成功
     */
    @PostMapping("/saveWorkData")
    @ApiOperation("/保存工作信息-app")
    public IResponse saveWorkData(@RequestBody @NotNull CustInfoCondition condition) {
        this.applyCustBaseInfoService.saveWorkData(condition);
        return IResponse.success("保存成功");
    }

    /**
     * 保存地址信息-app
     *
     * @param condition 地址信息
     * @return 保存成功
     */
    @PostMapping("/saveAddress")
    @ApiOperation("/保存地址信息-app")
    public IResponse saveAddress(@RequestBody @NotNull CustInfoCondition condition) {
        this.applyCustBaseInfoService.saveAddress(condition);
        return IResponse.success("保存成功");
    }


    /**
     * 更新客户信息/附件信息
     *
     * @param condition 客户信息/附件信息
     * @return 二维码/附件md5
     */
    @PostMapping("/updateSignParams")
    @ApiOperation("更新客户信息/附件信息")
    public IResponse updateSignParams(@RequestBody @NotNull CustInfoCondition condition) {
        List list = applyCustBaseInfoService.saveSignParams(condition);
        //生成征信授权书
        List<ComAttachmentFile> fileList = creatContractService.applyAuthorBatchPrint(condition.getBussinessType(), condition.getApplyNo(), condition.getCertNo(), AfsEnumUtil.key(ServiceClientTypeEnum.APP));
        list.add(fileList);
        return IResponse.success(list);
    }
}
